Page({
  data: {
    raceTime: '',
    raceTimeDisplay: '',
    raceLocation: '',
    showTimeModal: false,
    years: [],
    months: [],
    days: [],
    datePickerValue: [0, 0, 0],
    startTime: '16:00',
    endTime: '18:00',
    signupList: [null, null, null, null, null, null, null, null],
    signupCount: 0,
    showSignupAction: false,
    signupIndex: -1,
    showMatchModal: false,
    girlSetting: 'standard',
    matchCount: 9,
    matchList: [],
    disclaimerChecked: true,
    selectedItemIndex: 0,
    scoreModalVisible: false,
    scoreModalIndex: -1,
    scoreLeft: '',
    scoreRight: '',
    scoreModalLeft: [],
    scoreModalRight: [],
    resultList: [],
    userInfo: null,
    courtCount: 1,
    maxCourtCount: 1,
    safePaddingTop: 0,
    showGenderSelect: false,
    tempOtherName: '',
    tempOtherGender: 'male',
    showEditTitleModal: false,
    editTitleValue: '',
    raceTitle: '',
    defaultRaceTitle: '单打循环赛 | 7-3发布',
    showOtherSignupModal: false,
    finishedCount: 0,
    scoreTabIndex: 0,
    scoreTabList: [
      { title: '全部', count: 0 },
      { title: '未结束', count: 0 },
      { title: '可以比赛', count: 0 },
      { title: '比赛中', count: 0 }
    ],
    filteredMatchList: [],
    showRegenMatchBtn: false,
    maxPlayers: 8,
    appliedCount: 0,
    recommendMatchCountList: [], // 新增：推荐局数列表
    isCustomMatchCount: false,
    customMatchCount: '',
    showQuickSignupModal: false,
    quickSignupText: '',
    quickSignupPreviewPages: [],
    quickSignupPreviewPageIndex: 0,
    quickSignupPreviewPageSize: 15,
    editSignupIndex: -1, // 新增：编辑报名时记录索引
    editSignupName: '', // 新增：编辑报名时记录昵称
    editSignupGender: 'male', // 新增：编辑报名时记录性别
    showEditSignupModal: false, // 新增：编辑报名弹窗是否显示
    modalOpen: false, // 防止多次弹窗
    raceInfo: null,
    shareImagePath: '', // 存储生成的分享图路径
    shareTitle: '羽毛球比赛邀请',
    sharePath: '/pages/singlePlay/singlePlay',
    isCreator: false, // 是否为创建人
    roundType: 'single', // 比赛循环次数：single-单循环，double-双循环，custom-自定义
    customRoundCount: 3 // 自定义循环次数
  },
  onLoad(options) {
    if (!options.id) {
      wx.showToast({ title: '缺少比赛ID', icon: 'none' });
      setTimeout(() => wx.navigateBack(), 1500);
      return;
    }
    this.options = options;
    this.raceId = options.id;
    
    // 引入本地数据管理器
    const localDataManager = require('../../utils/localDataManager.js');
    this.localDataManager = localDataManager;
    
    // 获取系统状态栏和导航栏高度
    wx.getWindowInfo({
      success: res => {
        const statusBarHeight = res.statusBarHeight || 20;
        const navBarHeight = 44; // 可根据实际微调
        this.setData({
          safePaddingTop: statusBarHeight + navBarHeight
        });
      }
    });
    
    // 从本地存储加载比赛基本信息
    const raceId = options.id;
    const raceData = localDataManager.getRace(raceId);
    
    if (!raceData) {
      wx.showToast({ title: '比赛不存在', icon: 'none' });
      setTimeout(() => wx.navigateBack(), 1500);
      return;
    }
    
    // 获取用户信息
    const userInfo = getApp().globalData.userInfo;
    
    // 判断是否为创建人
    const isCreator = userInfo && raceData.creator &&
      (userInfo.userId === raceData.creator.userId ||
       userInfo.phone === raceData.creator.phone);
    
    // 初始化日期选择器
    this.initDatePicker();
    
    // 检查是否有已生成的比赛
    const existingMatches = localDataManager.getMatches(raceId);
    let showRegenMatchBtn = false;
    let selectedItemIndex = 0;
    
    if (existingMatches && existingMatches.length > 0) {
      showRegenMatchBtn = true;
    }
    
    // 根据比赛状态设置初始tab
    if (raceData.status === '计分中') {
      selectedItemIndex = 1;
      showRegenMatchBtn = true;
    } else if (raceData.status === '已完赛') {
      selectedItemIndex = 2;
      showRegenMatchBtn = true;
    }
    
    // 设置比赛基本信息
    this.setData({
      raceInfo: raceData,
      raceTitle: raceData.title || this.data.defaultRaceTitle,
      raceTime: raceData.time || '',
      raceTimeDisplay: raceData.timeDisplay || '',
      raceLocation: raceData.location || '',
      courtCount: raceData.courtCount || 1,
      maxPlayers: raceData.maxPlayers || 8,
      userInfo: userInfo,
      isCreator: isCreator,
      showRegenMatchBtn: showRegenMatchBtn,
      selectedItemIndex: selectedItemIndex
    });
    
    // 加载报名列表
    this.loadSignupList();
    
         // 加载比赛列表
     this.loadMatchList();
     
     // 计算推荐局数
     this.calculateRecommendMatchCount();
     
     // 如果比赛已完赛，计算成绩
     if (raceData.status === '已完赛') {
       // 延迟计算成绩，确保数据已加载完成
       setTimeout(() => {
         this.calculateResults();
       }, 100);
     }
  },
  
     onShow() {
     // 重新加载数据
     this.loadSignupList();
     this.loadMatchList();
     
     // 如果当前在成绩标签页且比赛已完赛，重新计算成绩
     if (this.data.selectedItemIndex === 2) {
       const raceData = this.localDataManager.getRace(this.raceId);
       if (raceData && raceData.status === '已完赛') {
         setTimeout(() => {
           this.calculateResults();
         }, 100);
       }
     }
   },
  
  // 初始化日期选择器
  initDatePicker() {
    const now = new Date();
    const years = [];
    const months = [];
    const days = [];
    
    for (let i = now.getFullYear(); i <= now.getFullYear() + 1; i++) {
      years.push(i);
    }
    for (let i = 1; i <= 12; i++) {
      months.push(i);
    }
    for (let i = 1; i <= 31; i++) {
      days.push(i);
    }
    
    this.setData({
      years: years,
      months: months,
      days: days,
      datePickerValue: [0, now.getMonth(), now.getDate() - 1]
    });
  },
  
  // 计算推荐局数
  calculateRecommendMatchCount() {
    const signupCount = this.data.signupCount;
    if (signupCount < 3) {
      this.setData({
        recommendMatchCountList: [3, 5, 7]
      });
      return;
    }
    
    // 单打循环赛的推荐局数
    const recommendCounts = [];
    if (signupCount >= 3) recommendCounts.push(3);
    if (signupCount >= 4) recommendCounts.push(5);
    if (signupCount >= 5) recommendCounts.push(7);
    if (signupCount >= 6) recommendCounts.push(9);
    
    this.setData({
      recommendMatchCountList: recommendCounts
    });
  },
  
  // 生成公平轮换算法（单打版本）
  generateFairRotation(players, totalMatches, courts) {
    const n = players.length;
    if (n < 3) {
      console.log('玩家数量不足，无法生成比赛');
      return [];
    }
    
    let matchList = [];
    
    // 使用经典的循环赛算法（轮转法）
    // 将选手编号为 0, 1, 2, ..., n-1
    let playerIds = Array.from({length: n}, (_, i) => i);
    
    // 如果选手数量是奇数，添加一个"轮空"选手
    if (n % 2 === 1) {
      playerIds.push(-1); // -1 表示轮空
    }
    
    const numRounds = playerIds.length - 1;
    const matchesPerRound = Math.floor(playerIds.length / 2);
    
    for (let round = 0; round < numRounds; round++) {
      // 为当前轮次生成比赛
      for (let match = 0; match < matchesPerRound; match++) {
        const player1Index = match;
        const player2Index = playerIds.length - 1 - match;
        
        // 跳过轮空的比赛
        if (playerIds[player1Index] === -1 || playerIds[player2Index] === -1) {
          continue;
        }
        
        // 获取实际选手
        const player1 = players[playerIds[player1Index]];
        const player2 = players[playerIds[player2Index]];
        
        // 跳过自己vs自己的比赛
        if (playerIds[player1Index] === playerIds[player2Index]) {
          continue;
        }
        
        matchList.push({
          left: [player1],
          right: [player2],
          status: 'ready',
          round: round + 1,
          courtIndex: match % courts
        });
      }
      
      // 轮转：除了第一个选手，其他选手顺时针轮转
      const temp = playerIds[playerIds.length - 1];
      for (let i = playerIds.length - 1; i > 1; i--) {
        playerIds[i] = playerIds[i - 1];
      }
      playerIds[1] = temp;
    }
    
    // 如果生成的比赛数量超过要求，只取前totalMatches场
    if (matchList.length > totalMatches) {
      matchList = matchList.slice(0, totalMatches);
    }
    

    return matchList;
  },
  
  // 生成海报
  async generatePoster() {
    try {
      const ctx = wx.createCanvasContext('posterCanvas', this);
      
      // 1. 绘制背景
      ctx.setFillStyle('#ffffff');
      ctx.fillRect(0, 0, 300, 500);
      
      // 2. 绘制内容（添加错误处理）
      //await this.drawImageWithFallback(ctx, '/images/badminton.jpeg', 20, 20, 260, 260);
      
      // 3. 绘制文字
      ctx.setFontSize(18);
      ctx.setFillStyle('#333333');
      ctx.fillText('羽毛球比赛', 30, 300);
      
      // 4. 生成临时文件
      const tempFilePath = await new Promise((resolve, reject) => {
        ctx.draw(false, () => {
          setTimeout(() => {
            wx.canvasToTempFilePath({
              canvasId: 'posterCanvas',
              success: (res) => resolve(res.tempFilePath),
              fail: reject
            }, this);
          }, 300);
        });
      });
      
      this.setData({ tempFilePath, posterReady: true });
      return tempFilePath;
      
    } catch (err) {
      console.error('生成海报失败:', err);
      throw err;
    }
  },

  // 带错误处理的图片绘制
  drawImageWithFallback(ctx, imgPath, x, y, width, height) {
    return new Promise((resolve) => {
      wx.getImageInfo({
        src: imgPath,
        success: (res) => {
          ctx.drawImage(res.path, x, y, width, height);
          resolve();
        },
        fail: (err) => {
          console.error('图片加载失败:', imgPath, err);
          // 绘制默认背景
          ctx.setFillStyle('#f0f0f0');
          ctx.fillRect(x, y, width, height);
          resolve();
        }
      });
    });
  },

  // 点击分享按钮
  async handleShare() {
    if (!this.data.tempFilePath) {
      wx.showLoading({ title: '生成分享图中...' });
      try {
        await this.generatePoster();
      } catch (err) {
        wx.showToast({ title: '生成分享图失败', icon: 'none' });
        wx.hideLoading();
        return;
      }
      wx.hideLoading();
    }
    
  },

  // 分享配置
  onShareAppMessage() {
    const id = this.data.raceId || (this.options && this.options.id) || '';
    return {
      title: this.data.shareTitle,
      path: `/pages/singlePlay/singlePlay?id=${id}`
      // 不设置 imageUrl，让微信自动生成页面内容卡片
    };
  },
  // 朋友圈分享
  onShareTimeline() {
    const id = this.data.raceId || (this.options && this.options.id) || '';
    return {
      title: this.data.shareTitle,
      query: `id=${id}&from=timeline`
      // 不设置 imageUrl
    };
  },
  
  // 生成对阵
  onGenerateMatch() {
    if (this.data.signupCount < 3) {
      wx.showToast({ title: '至少需要3人才能开始比赛', icon: 'none' });
      return;
    }
    
    this.setData({
      showMatchModal: true
    });
  },
  
  // 确认生成对阵
  onConfirmMatchModal() {
    this._doGenerateMatch();
  },
  
  // 执行生成对阵
  _doGenerateMatch() {
    const signupList = this.data.signupList.filter(player => player && player.nickName);
    const courtCount = this.data.courtCount;
    
    if (signupList.length < 3) {
      wx.showToast({ title: '至少需要3人才能开始比赛', icon: 'none' });
      return;
    }
    
    // 根据循环次数计算总场数
    const playerCount = signupList.length;
    let totalMatches;
    
    switch (this.data.roundType) {
      case 'single':
        // 单循环：每个玩家与其他所有玩家各打一场
        totalMatches = playerCount * (playerCount - 1) / 2;
        break;
      case 'double':
        // 双循环：每个玩家与其他所有玩家各打两场
        totalMatches = playerCount * (playerCount - 1);
        break;
      case 'custom':
        // 自定义：使用用户输入的循环次数
        const customCount = this.data.customRoundCount || 3;
        totalMatches = playerCount * (playerCount - 1) / 2 * customCount;
        break;
      default:
        // 默认使用单循环
        totalMatches = playerCount * (playerCount - 1) / 2;
    }
    
    // 生成比赛列表
    const matchList = this.generateFairRotation(signupList, totalMatches, courtCount);

    // 保存到本地存储（统一使用纯数组格式）
    this.localDataManager.saveMatches(this.raceId, matchList);

    // 将比赛状态重置为“计分中”，覆盖“已完赛”等历史状态
    const raceData = this.localDataManager.getRace(this.raceId);
    if (raceData) {
      raceData.status = '计分中';
      this.localDataManager.saveRace(raceData);
    }

    // 更新界面
    this.loadMatchList();
    
    this.setData({
      showMatchModal: false,
      showRegenMatchBtn: true,
      selectedItemIndex: 1,  // 自动切换到对局计分页面
      finishedCount: 0,
      resultList: []
    });
    
    wx.showToast({ 
      title: '对阵已生成', 
      icon: 'success'
    });
  },
  

  
  // 关闭生成对阵弹窗
  onCloseMatchModal() {
    this.setData({
      showMatchModal: false
    });
  },
  
  // 选择循环类型
  onSelectRoundType(e) {
    const roundType = e.detail.value;
    this.setData({
      roundType: roundType
    });
  },
  
  // 自定义循环次数输入
  onCustomRoundCountInput(e) {
    this.setData({
      customRoundCount: parseInt(e.detail.value) || 3
    });
  },
  
  // 返回上一页
  onBack() {
    wx.navigateBack({
      fail: () => {
        wx.switchTab({
          url: '/pages/index/index'
        });
      }
    });
  },
  
  // 加载报名列表
  loadSignupList() {
    const raceId = this.raceId;
    if (!raceId) {
      return;
    }
    
    // 从本地存储加载报名列表
    const signupDataList = this.localDataManager.getSignups(raceId);
    
    let maxPlayers = this.data.maxPlayers || 8;
    
    // 创建固定长度的数组，保持位置信息
    let signupList = new Array(maxPlayers).fill(null);
    
    if (signupDataList && signupDataList.length > 0) {
      // 将报名数据按order放置到对应位置
      signupDataList.forEach(item => {
        if (typeof item.order === 'number' && item.order >= 0 && item.order < maxPlayers) {
          const signupItem = {};
          // 复制userInfo的所有属性
          if (item.userInfo) {
            for (let key in item.userInfo) {
              if (item.userInfo.hasOwnProperty(key)) {
                signupItem[key] = item.userInfo[key];
              }
            }
          }
          signupItem._id = item._id;
          signupItem.order = item.order;
          signupList[item.order] = signupItem;
        }
      });
    }
    
    let actualCount = signupList.filter(item => item !== null).length;
    
    if (actualCount > maxPlayers) {
      maxPlayers = actualCount;
      // 更新本地存储中的比赛信息
      const raceData = this.localDataManager.getRace(raceId);
      if (raceData) {
        raceData.maxPlayers = maxPlayers;
        this.localDataManager.saveRace(raceData);
      }
      // 重新调整数组长度
      while (signupList.length < maxPlayers) {
        signupList.push(null);
      }
    }
    
    this.setData({
      signupList: signupList,
      signupCount: actualCount,
      maxPlayers: maxPlayers
    });
    
    // 重新计算推荐局数
    this.calculateRecommendMatchCount();
  },
  
  // 加载比赛列表
  loadMatchList() {
    const matchData = this.localDataManager.getMatches(this.raceId);
    
    // 检查数据格式：如果是对象数组且包含 matchList 属性，则取 matchList
    let matchList;
    if (matchData && matchData.length && matchData[0] && matchData[0].matchList) {
      matchList = matchData[0].matchList;
    } else {
      // 否则直接使用 matchData
      matchList = matchData || [];
    }
    
    const finishedCount = matchList.filter(match => match.status === 'finished').length;
    
    this.setData({
      matchList: matchList,
      finishedCount: finishedCount
    });
    
    // 更新计分页面标签
    this.updateScoreTabs();
    
    // 过滤比赛列表
    this.filterMatchList();
  },
  
  // 更新计分页面标签
  updateScoreTabs() {
    const matchList = this.data.matchList;
    const totalCount = matchList.length;
    const finishedCount = matchList.filter(m => m.status === 'finished').length;
    const readyCount = matchList.filter(m => m.status === 'ready').length;
    const playingCount = matchList.filter(m => m.status === 'playing').length;
    
    this.setData({
      'scoreTabList[0].count': totalCount,
      'scoreTabList[1].count': totalCount - finishedCount,
      'scoreTabList[2].count': readyCount,
      'scoreTabList[3].count': playingCount
    });
  },
  
  // 过滤比赛列表
  filterMatchList() {
    const matchList = this.data.matchList;
    const scoreTabIndex = this.data.scoreTabIndex;
    

    let filteredList = [];
    
    switch (scoreTabIndex) {
      case 0: // 全部
        filteredList = matchList;
        break;
      case 1: // 未结束
        filteredList = matchList.filter(match => match.status !== 'finished');
        break;
      case 2: // 可以比赛
        filteredList = matchList.filter(match => match.status === 'ready');
        break;
      case 3: // 比赛中
        filteredList = matchList.filter(match => match.status === 'playing');
        break;
    }
    
    this.setData({
      filteredMatchList: filteredList
    });
  },
  
  // 切换标签页
  onTabChange(e) {
    const idx = Number(e.currentTarget.dataset.index);
    if (idx === 2) {
      // 统计成绩，按个人统计
      this.calculateResults();
      this.setData({ selectedItemIndex: idx });
    } else {
      this.setData({ selectedItemIndex: idx });
    }
  },
  
  // 计分页面标签切换
  onScoreTabChange(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      scoreTabIndex: index
    });
    this.filterMatchList();
  },
  
  // 刷新计分
  onScoreRefresh() {
    this.loadMatchList();
    wx.showToast({ title: '已刷新', icon: 'success' });
  },
  
  // 开始比赛
  onStartMatch(e) {
    const filteredIndex = e.currentTarget.dataset.index;
    const filteredMatchList = this.data.filteredMatchList;
    const target = filteredMatchList[filteredIndex];
    
    if (!target) return;
    
    // 在原始matchList中找到对应的索引
    const matchList = this.data.matchList;
    const realIndex = matchList.findIndex(item => 
      JSON.stringify(item) === JSON.stringify(target)
    );
    
    if (realIndex === -1) return;
    
    matchList[realIndex].status = 'playing';
    
    this.localDataManager.saveMatches(this.raceId, matchList);
    this.loadMatchList();
    
    wx.showToast({ title: '比赛已开始', icon: 'success' });
  },
  
  // 取消比赛
  onCancelMatch(e) {
    const filteredIndex = e.currentTarget.dataset.index;
    const filteredMatchList = this.data.filteredMatchList;
    const target = filteredMatchList[filteredIndex];
    
    if (!target) return;
    
    // 在原始matchList中找到对应的索引
    const matchList = this.data.matchList;
    const realIndex = matchList.findIndex(item => 
      JSON.stringify(item) === JSON.stringify(target)
    );
    
    if (realIndex === -1) return;
    
    matchList[realIndex].status = 'ready';
    
    this.localDataManager.saveMatches(this.raceId, matchList);
    this.loadMatchList();
    
    wx.showToast({ title: '比赛已取消', icon: 'success' });
  },
  
  // 打开计分弹窗
  onOpenScoreModal(e) {
    const filteredIndex = e.currentTarget.dataset.index;
    const filteredMatchList = this.data.filteredMatchList;
    const target = filteredMatchList[filteredIndex];
    
    if (!target) return;
    
    // 在原始matchList中找到对应的索引
    const matchList = this.data.matchList;
    const realIndex = matchList.findIndex(item => 
      JSON.stringify(item) === JSON.stringify(target)
    );
    
    if (realIndex === -1) return;
    
    this.setData({
      scoreModalVisible: true,
      scoreModalIndex: realIndex,
      scoreModalLeft: target.left,
      scoreModalRight: target.right,
      scoreLeft: target.score ? target.score.left.toString() : '',
      scoreRight: target.score ? target.score.right.toString() : ''
    });
  },
  
  // 关闭计分弹窗
  onCloseScoreModal() {
    this.setData({
      scoreModalVisible: false,
      scoreModalIndex: -1,
      scoreLeft: '',
      scoreRight: ''
    });
  },
  
  // 计分输入
  onScoreInput(e) {
    const side = e.currentTarget.dataset.side;
    const value = e.detail.value;
    
    // 只允许输入数字
    if (value && !/^\d*$/.test(value)) {
      wx.showToast({ title: '只能输入数字', icon: 'none' });
      return;
    }
    
    this.setData({
      [side]: value
    });
  },
  
  // 确认计分
  onConfirmScoreModal() {
    const { scoreLeft, scoreRight, scoreModalIndex } = this.data;
    
    if (scoreLeft === '' || scoreRight === '') {
      wx.showToast({ title: '请填写完整比分', icon: 'none' });
      return;
    }
    
    // 校验输入为数字
    if (isNaN(Number(scoreLeft)) || isNaN(Number(scoreRight))) {
      wx.showToast({ title: '比分只能输入数字', icon: 'none' });
      return;
    }
    
    const leftScore = parseInt(scoreLeft) || 0;
    const rightScore = parseInt(scoreRight) || 0;
    const index = scoreModalIndex;
    
    if (leftScore < 0 || rightScore < 0) {
      wx.showToast({ title: '比分不能为负数', icon: 'none' });
      return;
    }
    
    const matchList = this.data.matchList;
    matchList[index].score = {
      left: leftScore,
      right: rightScore
    };
    matchList[index].status = 'finished';
    
    // 保存为纯数组，保持与生成时一致
    this.localDataManager.saveMatches(this.raceId, matchList);
    this.loadMatchList();
    
    this.onCloseScoreModal();
    
    // 检查是否所有比赛都已完成
    const allMatchesFinished = matchList.every(match => match.status === 'finished');
    
    if (allMatchesFinished) {
      // 如果所有比赛都完成了，更新比赛状态为"已完赛"
      const raceData = this.localDataManager.getRace(this.raceId);
      if (raceData) {
        raceData.status = '已完赛';
        this.localDataManager.saveRace(raceData);
      }
      
      // 计算比赛成绩
      this.calculateResults();
      
      // 自动切换到比赛成绩tab
      this.setData({
        selectedItemIndex: 2
      }, () => {
        // 滚动到页面顶部
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 300
        });
      });
      wx.showToast({ title: '所有比赛已完成', icon: 'success' });
    } else {
      wx.showToast({ title: '比分已保存', icon: 'success' });
    }
  },
  
  // 计算比赛成绩
  calculateResults() {
    const matchList = this.data.matchList;
    const signupList = this.data.signupList.filter(player => player && player.nickName);
    
    // 初始化结果
    const results = signupList.map(player => ({
      name: player.nickName,
      avatarUrl: player.avatarUrl,
      gender: player.gender,
      win: 0,
      lose: 0,
      score: 0
    }));
    
    // 统计每场比赛的结果
    matchList.forEach(match => {
      if (match.status === 'finished' && match.score) {
        const leftPlayer = match.left[0];
        const rightPlayer = match.right[0];
        const leftScore = match.score.left;
        const rightScore = match.score.right;
        
        // 找到对应的玩家索引
        const leftIndex = signupList.findIndex(p => p.nickName === leftPlayer.nickName);
        const rightIndex = signupList.findIndex(p => p.nickName === rightPlayer.nickName);
        
        if (leftIndex !== -1 && rightIndex !== -1) {
          // 更新胜负场次
          if (leftScore > rightScore) {
            results[leftIndex].win++;
            results[rightIndex].lose++;
          } else if (rightScore > leftScore) {
            results[rightIndex].win++;
            results[leftIndex].lose++;
          }
          
          // 更新净胜分
          results[leftIndex].score += (leftScore - rightScore);
          results[rightIndex].score += (rightScore - leftScore);
        }
      }
    });
    
    // 按胜场数、净胜分排序
    results.sort((a, b) => {
      if (b.win !== a.win) {
        return b.win - a.win;
      }
      return b.score - a.score;
    });
    
    this.setData({
      resultList: results
    });
  },
  
  // 编辑标题
  onEditTitle() {
    this.setData({
      showEditTitleModal: true,
      editTitleValue: this.data.raceTitle
    });
  },
  
  onEditTitleInput(e) {
    this.setData({
      editTitleValue: e.detail.value
    });
  },
  
  onConfirmEditTitle() {
    const newTitle = this.data.editTitleValue.trim();
    if (!newTitle) {
      wx.showToast({ title: '标题不能为空', icon: 'none' });
      return;
    }
    
    // 更新比赛信息
    const raceData = this.localDataManager.getRace(this.raceId);
    if (raceData) {
      raceData.title = newTitle;
      this.localDataManager.saveRace(raceData);
    }
    
    this.setData({
      raceTitle: newTitle,
      showEditTitleModal: false
    });
    
    wx.showToast({ title: '标题已更新', icon: 'success' });
  },
  
  onCancelEditTitle() {
    this.setData({
      showEditTitleModal: false
    });
  },
  
  // 编辑时间
  onEditTime() {
    this.setData({
      showTimeModal: true
    });
  },
  
  onCloseTimeModal() {
    this.setData({
      showTimeModal: false
    });
  },
  
  onDateChange(e) {
    this.setData({
      datePickerValue: e.detail.value
    });
  },
  
  onStartTimeChange(e) {
    this.setData({
      startTime: e.detail.value
    });
  },
  
  onEndTimeChange(e) {
    this.setData({
      endTime: e.detail.value
    });
  },
  
  onConfirmTime() {
    const datePickerValue = this.data.datePickerValue;
    const year = this.data.years[datePickerValue[0]];
    const month = this.data.months[datePickerValue[1]];
    const day = this.data.days[datePickerValue[2]];
    const startTime = this.data.startTime;
    const endTime = this.data.endTime;
    
    const timeDisplay = `${year}年${month}月${day}日 ${startTime}-${endTime}`;
    
    // 更新比赛信息
    const raceData = this.localDataManager.getRace(this.raceId);
    if (raceData) {
      raceData.time = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${startTime}-${endTime}`;
      raceData.timeDisplay = timeDisplay;
      this.localDataManager.saveRace(raceData);
    }
    
    if (raceData) {
      this.setData({
        raceTime: raceData.time,
        raceTimeDisplay: timeDisplay,
        showTimeModal: false
      });
      
      wx.showToast({ title: '时间已更新', icon: 'success' });
    } else {
      wx.showToast({ title: '更新失败', icon: 'error' });
    }
  },
  
  // 编辑地点
  onEditLocation() {
    if (!this.data.isCreator) {
      wx.showToast({ title: '只有创建人才能修改', icon: 'none' });
      return;
    }
    
    wx.showModal({
      title: '编辑比赛地点',
      content: this.data.raceLocation || '',
      placeholderText: '请输入比赛地点',
      editable: true,
      success: (res) => {
        if (res.confirm && res.content) {
          const newLocation = res.content.trim();
          if (newLocation) {
            this.setData({
              raceLocation: newLocation
            });
            
            // 更新比赛信息
            const raceData = this.localDataManager.getRace(this.raceId);
            if (raceData) {
              raceData.location = newLocation;
              this.localDataManager.saveRace(raceData);
            }
            
            wx.showToast({ title: '地点修改成功', icon: 'success' });
          }
        }
      }
    });
  },
  

  
  // 场地数量变化
  onCourtRadioGroupChange(e) {
    const courtCount = parseInt(e.detail.value);
    this.setData({
      courtCount: courtCount
    });
    
    // 更新比赛信息
    const raceData = this.localDataManager.getRace(this.raceId);
    if (raceData) {
      raceData.courtCount = courtCount;
      this.localDataManager.saveRace(raceData);
    }
  },
  
  // 确保登录
  ensureLogin(callback) {
    let userInfo = this.data.userInfo || getApp().globalData.userInfo;
    if (userInfo && userInfo.isLogin) {
      callback();
    } else {
      wx.getUserProfile({
        desc: '用于完善用户资料',
        success: (res) => {
          const userInfo = {
            ...res.userInfo,
            isLogin: true
          };
          this.setData({ userInfo });
          getApp().globalData.userInfo = userInfo;
          callback();
        },
        fail: () => {
          wx.showToast({ title: '需要授权才能报名', icon: 'none' });
        }
      });
    }
  },
  
  // 报名相关方法
  onSignupTap(e) {
    const index = e.currentTarget.dataset.index;
    const { signupList } = this.data;
    const item = signupList[index];
    
    if (!item || !item.nickName || !item._id) {
      // 对于空位置，检查当前用户是否已经报名
      const currentUser = this.data.userInfo || getApp().globalData.userInfo;
      let hasSigned = false;
      if (currentUser && currentUser.nickName) {
        hasSigned = signupList.some(signup => 
          signup && signup.nickName && signup.nickName === currentUser.nickName
        );
      }
      this.setData({ showSignupAction: true, signupIndex: index, hasSigned: hasSigned });
      return;
    }
    
    // 对于已报名位置，需要登录才能编辑/取消
    this.ensureLogin(() => {
      wx.showActionSheet({
        itemList: ['编辑', '取消报名'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.setData({
              editSignupIndex: index,
              editSignupName: item.nickName,
              editSignupGender: item.gender || 'male',
              showEditSignupModal: true
            });
          } else if (res.tapIndex === 1) {
            wx.showModal({
              title: '取消报名',
              content: '确定要取消该报名吗？',
              confirmText: '取消报名',
              cancelText: '关闭',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  const raceId = this.options && this.options.id;
                  
                  // 从本地存储中删除报名
                  this.localDataManager.removeSignup(raceId, item._id);
                  wx.showToast({ title: '已取消报名' });
                  
                  // 更新比赛信息
                  const raceData = this.localDataManager.getRace(raceId);
                  if (raceData) {
                    raceData.courtCount = this.data.courtCount;
                    this.localDataManager.saveRace(raceData);
                  }
                  
                  this.loadSignupList();
                }
              }
            });
          }
        }
      });
    });
  },
  
  onCloseSignupAction() {
    this.setData({
      showSignupAction: false,
      signupIndex: -1
    });
  },
  
  onSignupSelf() {
    this.ensureLogin(() => {
      const userInfo = this.data.userInfo;
      if (!userInfo) {
        wx.showToast({ title: '请先登录', icon: 'none' });
        return;
      }
      
      // 兼容微信用户信息的 gender 字段（1男2女0未知）和字符串格式
      let gender = 'male';
      if (userInfo.gender === 2 || userInfo.gender === 'female') {
        gender = 'female';
      } else if (userInfo.gender === 1 || userInfo.gender === 'male') {
        gender = 'male';
      } else {
        // 如果性别未知，默认为男性
        gender = 'male';
      }
      
      // 根据性别设置头像
      let avatarUrl = userInfo.avatarUrl;
      if (gender === 'female') {
        avatarUrl = '../../images/avatar_girl.png';
      } else if (gender === 'male') {
        avatarUrl = '../../images/avatar_boy.png';
      }
      
      // Use the clicked position as order, maintaining position
      const order = this.data.signupIndex;
      
      // 添加到本地存储
      const signupData = {
        raceId: this.raceId,
        order: order,
        userInfo: {
          nickName: userInfo.nickName,
          avatarUrl: avatarUrl,
          gender: gender
        }
      };
      
      const success = this.localDataManager.addSignup(this.raceId, signupData);
      if (success) {
        wx.showToast({ title: '报名成功', icon: 'success' });
        
        // 更新比赛信息
        const raceData = this.localDataManager.getRace(this.raceId);
        if (raceData) {
          raceData.courtCount = this.data.courtCount;
          this.localDataManager.saveRace(raceData);
        }
        
        this.onCloseSignupAction();
        this.loadSignupList();
      } else {
        wx.showToast({ title: '报名失败', icon: 'none' });
      }
    });
  },
  
  onSignupOther() {
    this.setData({
      showOtherSignupModal: true,
      tempOtherName: '',
      tempOtherGender: 'male'
    });
  },
  
  onOtherNameInput(e) {
    this.setData({
      tempOtherName: e.detail.value
    });
  },
  
  onSelectGender(e) {
    this.setData({
      tempOtherGender: e.currentTarget.dataset.gender
    });
  },
  
  onConfirmOtherSignup() {
    const { signupIndex, tempOtherName, tempOtherGender } = this.data;
    if (!tempOtherName.trim()) {
      wx.showToast({ title: '请输入姓名', icon: 'none' });
      return;
    }
    
    let avatarUrl = '../../images/avatar_boy.png';
    if (tempOtherGender === 'female') {
      avatarUrl = '../../images/avatar_girl.png';
    }
    
    // Use the clicked position as order, maintaining position
    const order = signupIndex;
    
    // 添加到本地存储
    const signupData = {
      raceId: this.raceId,
      order: order,
      userInfo: {
        nickName: tempOtherName,
        avatarUrl: avatarUrl,
        gender: tempOtherGender
      }
    };
    
    const success = this.localDataManager.addSignup(this.raceId, signupData);
    
    if (success) {
      wx.showToast({ title: '报名成功', icon: 'success' });
      
      // 更新比赛信息
      const raceData = this.localDataManager.getRace(this.raceId);
      if (raceData) {
        raceData.courtCount = this.data.courtCount;
        this.localDataManager.saveRace(raceData);
      }
      
      this.setData({
        showOtherSignupModal: false,
        showSignupAction: false,
        signupIndex: -1,
        tempOtherName: '',
        tempOtherGender: 'male'
      }, () => {
        this.loadSignupList();
      });
    } else {
      wx.showToast({ title: '报名失败', icon: 'none' });
    }
  },
  
  onCancelOtherSignup() {
    this.setData({
      showOtherSignupModal: false,
      showSignupAction: false,
      signupIndex: -1
    });
  },
  
  // 编辑报名信息
  onEditSignupNameInput(e) {
    this.setData({
      editSignupName: e.detail.value
    });
  },
  
  onEditSignupGenderSelect(e) {
    this.setData({
      editSignupGender: e.currentTarget.dataset.gender
    });
  },
  
  onConfirmEditSignup() {
    const name = this.data.editSignupName.trim();
    if (!name) {
      wx.showToast({ title: '请输入姓名', icon: 'none' });
      return;
    }
    
    // 根据性别切换默认头像
    let avatarUrl = '../../images/avatar_boy.png';
    if (this.data.editSignupGender === 'female') {
      avatarUrl = '../../images/avatar_girl.png';
    }
    
    // 更新本地存储中的报名信息
    const { editSignupIndex, signupList } = this.data;
    const item = signupList[editSignupIndex];
    
    if (item && item._id) {
      const signupDataList = this.localDataManager.getSignups(this.raceId);
      const targetSignup = signupDataList.find(signup => signup._id === item._id);
      
      if (targetSignup) {
        targetSignup.userInfo.nickName = name;
        targetSignup.userInfo.gender = this.data.editSignupGender;
        targetSignup.userInfo.avatarUrl = avatarUrl;
        this.localDataManager.updateSignup(this.raceId, targetSignup);
        
        wx.showToast({ title: '编辑成功', icon: 'success' });
        this.setData({ showEditSignupModal: false });
        this.loadSignupList();
      } else {
        wx.showToast({ title: '编辑失败', icon: 'none' });
      }
    } else {
      wx.showToast({ title: '编辑失败', icon: 'none' });
    }
  },
  
  onCancelEditSignup() {
    this.setData({
      showEditSignupModal: false
    });
  },
  
  // 增加/减少报名位置
  onAddGroup() {
    // 增加报名位置只是UI层面的操作，不需要保存到本地存储
    const signupList = this.data.signupList;
    signupList.push(null);
    this.setData({ signupList });
  },
  
  onRemoveGroup() {
    const signupList = this.data.signupList;
    if (signupList.length > 3) {
      signupList.pop();
      this.setData({ signupList });
    } else {
      wx.showToast({ title: '至少需要3个位置', icon: 'none' });
    }
  },
  
  // 免责声明
  onDisclaimerChange(e) {
    this.setData({
      disclaimerChecked: e.detail.value
    });
  },
  
  onOpenDisclaimer() {
    wx.navigateTo({
      url: '/pages/disclaimer/disclaimer'
    });
  },
  
  // 公平轮换分组算法，强制任何选手不得连续参赛或连续休息超过2场，休息和参赛分布均匀



  onSelectGirlSetting(e) {
    this.setData({ girlSetting: e.currentTarget.dataset.value });
  },
  onSelectMatchCount(e) {
    const val = e.detail.value;
    if (val === 'custom') {
      this.setData({ isCustomMatchCount: true, matchCount: Number(this.data.customMatchCount) || 0 });
    } else {
      this.setData({ isCustomMatchCount: false, matchCount: Number(val) });
    }
  },
  onCustomMatchCountInput(e) {
    const val = e.detail.value;
    this.setData({
      customMatchCount: val,
      isCustomMatchCount: true,
      matchCount: Number(val) || 0
    });
  },








  updateCourtCountLimit() {
    const n = this.data.signupList.filter(item => item).length;
    let maxCourt = 1;
    if (n >= 16) maxCourt = 4;
    else if (n >= 12) maxCourt = 3;
    else if (n >= 8) maxCourt = 2;
    else maxCourt = 1;
    // 只更新maxCourtCount，不自动降档courtCount
    this.setData({ maxCourtCount: Math.max(1, maxCourt) });
  },
  onCourtCountChange(e) {
    this.setData({ courtCount: Number(e.detail.value) + 1 });
  },
  onAddCourt() {
    let { courtCount, maxCourtCount } = this.data;
    if (courtCount < maxCourtCount) {
      this.setData({ courtCount: courtCount + 1 });
    }
  },
  onSubCourt() {
    let { courtCount } = this.data;
    if (courtCount > 1) {
      this.setData({ courtCount: courtCount - 1 });
    }
  },





  setMatchProgress() {
    const matchList = this.data.matchList || [];
    const finishedCount = matchList.filter(item => item.status === 'finished').length;
    this.setData({ finishedCount });
  },



  onQuickSignup() {
    this.setData({ showQuickSignupModal: true, quickSignupText: '' });
  },
  
  onQuickSignupBtn() {
    this.setData({ showQuickSignupModal: true });
  },
  onCloseQuickSignup() {
    this.setData({ showQuickSignupModal: false, quickSignupText: '' });
  },
  onQuickSignupInput(e) {
    this.setData({ quickSignupText: e.detail.value });
  },
  onConfirmQuickSignup() {
    const text = this.data.quickSignupText || '';
    if (!text.trim()) {
      wx.showToast({ title: '请粘贴接龙内容', icon: 'none' });
      return;
    }
    
    // 逐行匹配，兼容多种点号和行首空格、全角空格、点号后空格
    const lines = text.split('\n').map(line => line.replace(/^\s+|\s+$/g, ''));
    const filterKeywords = ['场', '封车', '锁死', '钥匙'];
    // 允许点号后有任意空格，且点号可为.、．、。 、
    const names = lines
      .filter(line => /^[\s\u3000]*\d+[\.．。、]\s*[^\s]+/.test(line))
      .map(line => line.replace(/^[\s\u3000]*\d+[\.．。、]\s*/, ''))
      .filter(name => !filterKeywords.some(keyword => name.includes(keyword)));
    

    if (!names.length) {
      wx.showToast({ title: '请粘贴有效的接龙内容', icon: 'none' });
      return;
    }
    
    const defaultAvatar = '../../images/avatar_boy.png';
    const raceId = this.raceId;
    
    // 加 order 字段
    const signupList = names.map((name, idx) => ({ 
      nickName: name, 
      avatarUrl: defaultAvatar, 
      gender: 'male', 
      order: idx 
    }));
    

    wx.showModal({
      title: '提示',
      content: `将导入 ${names.length} 个报名，这会清空原来的报名信息，是否继续？`,
      confirmText: '导入',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 彻底清空报名，等待清空完成后再导入
          setTimeout(async () => { 
            await this.importSignupBatch(signupList, raceId); 
          }, 100);
        }
      }
    });
  },

  async importSignupBatch(signupList, raceId) {

    try {
      // 清空现有报名
      this.localDataManager.clearSignups(raceId);

      // 批量添加到本地存储
      for (const item of signupList) {
        const signupData = {
          raceId,
          order: item.order,
          userInfo: {
            nickName: item.nickName,
            avatarUrl: item.avatarUrl,
            gender: item.gender
          }
        };
        const result = this.localDataManager.addSignup(raceId, signupData);
      }

      wx.showToast({ title: '已导入报名', icon: 'success' });
      this.setData({ 
        showQuickSignupModal: false, 
        quickSignupText: '' 
      });
      
      // 导入后调试输出报名顺序
      const signupDataList = this.localDataManager.getSignups(raceId);
      const debugList = (signupDataList || []).map(item => ({
        order: item.order, 
        nickName: item.userInfo.nickName 
      }));

      // 重新加载报名列表
      this.loadSignupList();

    } catch (error) {
      console.error('[QuickSignup] 导入报名失败:', error);
      wx.showToast({ title: '导入失败，请重试', icon: 'none' });
    }
  }
});